package com.coding.springboot.demo.util;

import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class Util {
	// top_sing
	public static String sign(String parameter, String secret) throws Exception {
		// 对参数+密钥做MD5运算
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
		}

		byte[] digest = md.digest((parameter + secret).getBytes("utf-8"));
		// 对运算结果做BASE64运算并加密
		BASE64Encoder encode = new BASE64Encoder();
		return encode.encode(digest);
	}

	/**
	 * 生成md5
	 */
	public static String md5(String param) {
		String result = "";
		if (param == null || "".equals(param))
			return result;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byte2hex(md.digest(param.getBytes("utf-8")));
		} catch (Exception e) {
			throw new RuntimeException("md5 error !");
		}
		return result;
	}

	/**
	 * 新的md5签名，首尾放secret。
	 *
	 * @param secret
	 *            分配给您的APP_SECRET
	 */
	public static String md5Signature(TreeMap<String, String> params,
			String secret) {
		String result = null;
		StringBuffer orgin = getBeforeSign(params, new StringBuffer(secret));
		if (orgin == null)
			return result;
		orgin.append(secret);
		// //System.out.println("orgin="+orgin);
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byte2hex(md.digest(orgin.toString().getBytes("utf-8")));
		} catch (Exception e) {
			throw new RuntimeException("sign error !");
		}
		return result;
	}

	/**
	 * 添加参数的封装方法
	 */
	private static StringBuffer getBeforeSign(TreeMap<String, String> params,
			StringBuffer orgin) {
		if (params == null)
			return null;
		Map<String, String> treeMap = new TreeMap<String, String>();
		treeMap.putAll(params);
		Iterator<String> iter = treeMap.keySet().iterator();
		while (iter.hasNext()) {
			String name = (String) iter.next();
			orgin.append(name).append(params.get(name));
		}
		return orgin;
	}

	/**
	 * 二行制转字符串
	 */
	public static String byte2hex(byte[] b) {
		StringBuffer hs = new StringBuffer();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs.append("0").append(stmp);
			else
				hs.append(stmp);
		}
		return hs.toString().toUpperCase();
	}

	public static String getCurrDate() {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String currDateStr = format
				.format(new Date(System.currentTimeMillis()));
		return currDateStr;
	}

	// 返回一个随机数
	public static String getRandom() {
		Random random = new Random();
		return new Long(Math.abs(random.nextLong())).toString();
	}

	// WEB所在目录
	public static String getPath(Object object) {
		String path = object.getClass().getClassLoader().getResource("")
				.getPath().replace("%20", " ");
		return path.substring(1, path.indexOf("WEB-INF"));
	}

	// 返回两个日期相差的秒数
	public static long getTimeOut(String date1, String date2) throws Exception {
		return (SimpleDateFormat.getDateTimeInstance().parse(date2).getTime() - SimpleDateFormat
				.getDateTimeInstance().parse(date1).getTime()) / 1000;
	}

	// 检查logDate是否是当天
	public static boolean isToDay(Date logDate) {
		Calendar now = Calendar.getInstance();
		now.setTime(new Date());
		Calendar log = Calendar.getInstance();
		log.setTime(logDate);
		return (log.before(now) && now.get(now.YEAR) == log.get(log.YEAR) && now
				.get(now.DAY_OF_YEAR) == log.get(log.DAY_OF_YEAR));
	}

	public static String utf8Encode(String value) {
		String result = null;
		if (value != null) {
			try {
				result = new String(value.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	// 自发码加密串
	public static String before8Md5M(String src) throws Exception {
		return md5(src + src.length()).substring(8, 16) + "M";
	}

	/**
	 * 生成sha1
	 */
	public static String sha1(String param) {
		String result = "";
		if (param == null || "".equals(param))
			return result;
		try {
			MessageDigest md = MessageDigest.getInstance("SHA1");
			result = byte2hex(md.digest(param.getBytes("utf-8"))).toLowerCase();
		} catch (Exception e) {
			throw new RuntimeException("md5 error !");
		}
		return result;
	}

	/** 比较两个日期相差的月数 */
	public static int compareMonth(Date date1, Date date2) {
		if (date1 == null || date2 == null)
			return 0;

		int iMonth = 0;
		int flag = 0;
		try {
			Calendar objCalendarDate1 = Calendar.getInstance();
			objCalendarDate1.setTime(date1);

			Calendar objCalendarDate2 = Calendar.getInstance();
			objCalendarDate2.setTime(date2);

			if (objCalendarDate2.equals(objCalendarDate1))
				return 0;
			if (objCalendarDate1.after(objCalendarDate2)) {
				Calendar temp = objCalendarDate1;
				objCalendarDate1 = objCalendarDate2;
				objCalendarDate2 = temp;
			}

			if (objCalendarDate2.get(Calendar.YEAR) > objCalendarDate1
					.get(Calendar.YEAR))
				iMonth = ((objCalendarDate2.get(Calendar.YEAR) - objCalendarDate1
						.get(Calendar.YEAR))
						* 12 + objCalendarDate2.get(Calendar.MONTH) - flag)
						- objCalendarDate1.get(Calendar.MONTH);
			else
				iMonth = objCalendarDate2.get(Calendar.MONTH)
						- objCalendarDate1.get(Calendar.MONTH) - flag;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return iMonth;
	}

	public static Date addDate(Date date, String type, int addNum) {
		if (date == null)
			return null;

		if (type == null || type.trim().equals(""))
			return null;

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		if (type.equals("1")) {
			calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + addNum);
		} else if (type.equals("2")) {
			calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + addNum);
		} else if (type.equals("3")) {
			calendar.set(Calendar.DAY_OF_MONTH, calendar
					.get(Calendar.DAY_OF_MONTH)
					+ addNum);
		} else if (type.equals("4")) {
			calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR_OF_DAY)
					+ addNum);
		} else if (type.equals("5")) {
			calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE)
					+ addNum);
		}

		return calendar.getTime();
	}

	public static String utf8ToIso(String s) {
		String ret = "";
		try {
			ret = new String(s.getBytes("UTF-8"), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return ret;
	}

	// 格式化金额
	public static String formatMoney(String ptn, double money) {
		DecimalFormat df = new DecimalFormat();
		df.applyPattern(ptn);
		return df.format(money);
	}

	// 提出Map值到另一map
	public static Map<String, String> reqMapToMap(Map map) {
		Map<String, String> tmpRstMap = new HashMap<String, String>();
		Set tmpKeySet = map.keySet();
		for (Iterator tmpIt = tmpKeySet.iterator(); tmpIt.hasNext();) {
			Object tmpKey = tmpIt.next();
			Object tmpVal = map.get(tmpKey);
			if (tmpVal instanceof Object[]) {
				tmpVal = ((Object[]) tmpVal)[0];
			}
			tmpRstMap.put(tmpKey.toString(), tmpVal.toString());
		}

		return tmpRstMap;
	}

	public static Date setHMS(Date date, int h, int m, int s) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.HOUR_OF_DAY, h);
		c.set(Calendar.MINUTE, m);
		c.set(Calendar.SECOND, s);

		return c.getTime();
	}

	public static String cutString(String source, int maxLen) {
		if (source != null && maxLen >= 0) {
			source = source.length() > maxLen ? source.substring(0, maxLen)
					: source;
		}

		return source;
	}

	// 加1补0, 如: 15--> 00016
	public static String patchZero(Long count, int maxLen) {
		count = count == null ? 0L : count + 1;
		StringBuffer sb = new StringBuffer(count.toString());
		int len = maxLen - sb.length();
		if (len > 0) {
			for (int i = 0; i < len; i++) {
				sb.insert(0, "0");
			}
		}

		return sb.toString();
	}

	/**
	 * 判断double类型值是否int
	 * @param value
	 * @return
	 */
	public static boolean isInt(double value) {
		return (value % 1d) == 0d;
	}

	/**
	 * 判断double类型值是否int,并返回
	 * @return
	 */
	public static String getNumberStr(double d) {
		int i = (int) d;
		if (i == d) {
			return String.valueOf(i);
		} else {
			return String.valueOf(d);
		}
	}

	// 测试
	public static void main(String[] args) throws Exception {
		System.out.println(patchZero(3L, 2));
	}
}
